<template>
  <div v-if="aiAssistant" class="ai-assistant">
    <!-- AI助手小精灵 -->
    <div class="ai-sprite" :class="{ 'chat-open': chatVisible }" @click="toggleChat">
      <el-icon class="sprite-icon">
        <ChatDotRound />
      </el-icon>
      <div class="sprite-glow"></div>
    </div>

    <!-- 聊天窗口 -->
    <div
      v-if="chatVisible"
      ref="dialogRef"
      class="ai-chat-window"
      :class="{ 'is-dragging': isDragging }"
      :style="style"
    >
      <!-- 拖拽手柄 -->
      <div ref="dragHandle" class="drag-handle">
        <div class="window-header">
          <div class="header-left">
            <span class="window-title">AI助手</span>
            <span class="session-info">
              <span v-if="userMessageCount > 0" class="message-count">{{ userMessageCount }}条对话</span>
              <span class="session-status" :class="{ connected: sessionId }">{{ sessionId ? '已连接' : '未连接' }}</span>
            </span>
          </div>
          <div class="header-actions">
            <button class="action-btn" @click="clearChat" title="清空对话" :disabled="userMessageCount === 0">
              <el-icon><Delete /></el-icon>
            </button>
            <div class="drag-indicator">⋮⋮</div>
            <button class="close-btn" @click="chatVisible = false">
              <el-icon><Close /></el-icon>
            </button>
          </div>
        </div>
      </div>
      <div class="chat-container">
        <!-- 消息列表 -->
        <div class="message-list" ref="messageListRef">
          <div v-for="(message, index) in messages" :key="index" class="message-item" :class="message.type">
            <div class="message-content">
              <div class="message-text" v-html="renderMarkdown(message.content)"></div>
              <div class="message-time">{{ message.time }}</div>
            </div>
          </div>
          <div v-if="loading" class="message-item assistant">
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入框 -->
        <div class="input-area">
          <el-input v-model="inputMessage" placeholder="请输入您的问题..." @keyup.enter="sendMessage" :disabled="loading">
            <template #append>
              <el-button type="primary" @click="sendMessage" :loading="loading" :disabled="!inputMessage.trim()">
                发送
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch, onMounted, onUnmounted } from "vue";
import { storeToRefs } from "pinia";
import { useGlobalStore } from "@/stores/modules/global";
import { sendChatMessage, sendChatMessageStream } from "@/api/modules/chat";
import { ElMessage } from "element-plus";
import { ChatDotRound, Close, Delete } from "@element-plus/icons-vue";
import { useDraggable } from "@vueuse/core";
import { renderMarkdown } from "@/utils/markdown";

const globalStore = useGlobalStore();
const { aiAssistant } = storeToRefs(globalStore);

const chatVisible = ref(false);
const inputMessage = ref("");
const loading = ref(false);
const messageListRef = ref();
const sessionId = ref<string>("");

// 计算用户消息数量（排除系统欢迎消息）
const userMessageCount = computed(() => {
  return messages.value.filter(msg => msg.type === 'user').length;
});

// 拖拽相关状态
const dialogRef = ref();
const dragHandle = ref();

// 使用 VueUse 的 useDraggable
const { x, y, isDragging, style } = useDraggable(dialogRef, {
  initialValue: { x: window.innerWidth - 620, y: 100 },
  handle: dragHandle,
  preventDefault: true,
  stopPropagation: true,
});

interface Message {
  type: "user" | "assistant";
  content: string;
  time: string;
}

const messages = ref<Message[]>([]);

// 保存会话到本地存储
const saveSession = () => {
  const sessionData = {
    sessionId: sessionId.value,
    messages: messages.value,
    timestamp: new Date().toISOString()
  };
  localStorage.setItem('ai_assistant_session', JSON.stringify(sessionData));
};

// 从本地存储加载会话
const loadSession = () => {
  try {
    const savedSession = localStorage.getItem('ai_assistant_session');
    if (savedSession) {
      const sessionData = JSON.parse(savedSession);
      // 检查会话是否是今天的（可选：只保留当天会话）
      const sessionDate = new Date(sessionData.timestamp);
      const today = new Date();
      
      if (sessionDate.toDateString() === today.toDateString()) {
        sessionId.value = sessionData.sessionId;
        messages.value = sessionData.messages;
        return true;
      }
    }
  } catch (error) {
    console.error('加载会话失败:', error);
  }
  return false;
};

// 初始化会话
const initSession = () => {
  // 尝试加载已保存的会话
  if (!loadSession()) {
    // 如果没有保存的会话，创建新会话
    sessionId.value = 'assistant_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    
    // 添加欢迎消息
    messages.value = [{
      type: "assistant",
      content: "您好！我是AI助手，有什么可以帮助您的吗？",
      time: new Date().toLocaleTimeString()
    }];
    
    saveSession();
  }
};

// 清空对话
const clearChat = () => {
  // 清除本地存储
  localStorage.removeItem('ai_assistant_session');
  
  // 生成新的会话ID
  sessionId.value = 'assistant_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  
  // 重置消息
  messages.value = [{
    type: "assistant",
    content: "对话已清空。有什么新的问题需要帮助吗？",
    time: new Date().toLocaleTimeString()
  }];
  
  // 保存新会话
  saveSession();
};

// 组件挂载时初始化会话
onMounted(() => {
  initSession();
});

const toggleChat = () => {
  chatVisible.value = !chatVisible.value;
  // 如果是首次打开且没有会话ID，则初始化
  if (chatVisible.value && !sessionId.value) {
    initSession();
  }
};

const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
    }
  });
};

const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return;

  const userMessage = inputMessage.value.trim();

  // 添加用户消息
  messages.value.push({
    type: "user",
    content: userMessage,
    time: new Date().toLocaleTimeString()
  });

  inputMessage.value = "";
  loading.value = true;
  
  // 保存用户消息
  saveSession();
  scrollToBottom();

  // 添加一个空的AI消息，用于流式更新
  const aiMessageIndex = messages.value.length;
  messages.value.push({
    type: "assistant",
    content: "",
    time: new Date().toLocaleTimeString()
  });

  try {
    await sendChatMessageStream(
      { 
        message: userMessage,
        memoryId: sessionId.value 
      },
      // onMessage - 处理每个数据块
      (chunk: string) => {
        // 累积内容到AI消息中
        messages.value[aiMessageIndex].content += chunk;
        scrollToBottom();
      },
      // onComplete - 流结束
      () => {
        loading.value = false;
        // 如果没有收到任何内容，显示默认消息
        if (!messages.value[aiMessageIndex].content.trim()) {
          messages.value[aiMessageIndex].content = "抱歉，我暂时无法回答这个问题。";
        }
        // 保存会话
        saveSession();
        scrollToBottom();
      },
      // onError - 错误处理
      (error: any) => {
        console.error("发送消息失败:", error);
        ElMessage.error("发送消息失败，请稍后重试");
        
        messages.value[aiMessageIndex].content = "抱歉，服务暂时不可用，请稍后重试。";
        loading.value = false;
        // 保存会话（包括错误消息）
        saveSession();
        scrollToBottom();
      }
    );
  } catch (error) {
    console.error("发送消息失败:", error);
    ElMessage.error("发送消息失败，请稍后重试");
    
    messages.value[aiMessageIndex].content = "抱歉，服务暂时不可用，请稍后重试。";
    loading.value = false;
    // 保存会话（包括错误消息）
    saveSession();
    scrollToBottom();
  }
};

// 边界检测
watch([x, y], () => {
  // 确保窗口不会超出屏幕边界
  const maxX = window.innerWidth - 600;
  const maxY = window.innerHeight - 500;
  
  if (x.value > maxX) x.value = maxX;
  if (y.value > maxY) y.value = maxY;
  if (x.value < 0) x.value = 0;
  if (y.value < 0) y.value = 0;
});

// 监听消息变化，自动滚动到底部
watch(
  messages,
  () => {
    scrollToBottom();
  },
  { deep: true }
);
</script>

<style scoped lang="scss">
.ai-assistant {
  position: fixed;
  bottom: 200px;
  right: 80px;
  z-index: 9999;
}

.ai-sprite {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  &:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 25px rgba(102, 126, 234, 0.6);
  }

  &.chat-open {
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  }

  .sprite-icon {
    font-size: 24px;
    color: white;
    z-index: 2;
  }

  .sprite-glow {
    position: absolute;
    top: -2px;
    left: -2px;
    right: -2px;
    bottom: -2px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 50%;
    opacity: 0.7;
    animation: pulse 2s infinite;
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 0.7;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.4;
  }
  100% {
    transform: scale(1);
    opacity: 0.7;
  }
}

.ai-chat-window {
  position: fixed;
  width: 600px;
  height: 580px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  z-index: 9999;
  overflow: hidden;
  transition: box-shadow 0.3s ease;

  &.is-dragging {
    box-shadow: 0 15px 50px rgba(0, 0, 0, 0.2);
    user-select: none;
  }

  @media (max-width: 768px) {
    width: 90vw;
    height: 70vh;
  }
}

.drag-handle {
  cursor: grab;
  
  &:active {
    cursor: grabbing;
  }
}

.window-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  user-select: none;
  border-radius: 12px 12px 0 0;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.window-title {
  font-weight: 600;
  font-size: 16px;
}

.session-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.message-count {
  font-size: 12px;
  opacity: 0.8;
  color: rgba(255, 255, 255, 0.8);
}

.session-status {
  font-size: 10px;
  opacity: 0.6;
  color: rgba(255, 255, 255, 0.6);
  
  &.connected {
    color: #90EE90;
    opacity: 0.8;
  }
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  opacity: 0.8;

  &:hover:not(:disabled) {
    background-color: rgba(255, 255, 255, 0.1);
    opacity: 1;
  }

  &:disabled {
    opacity: 0.3;
    cursor: not-allowed;
  }

  .el-icon {
    font-size: 14px;
  }
}

.drag-indicator {
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
  letter-spacing: 2px;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;

  &:hover {
    background-color: rgba(255, 255, 255, 0.1);
  }

  .el-icon {
    font-size: 16px;
  }
}

.chat-container {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  background: #f8f9fa;
  cursor: default; // 消息区域不显示拖拽光标

  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: #ddd;
    border-radius: 2px;
  }
}

.message-item {
  margin-bottom: 15px;
  display: flex;

  &.user {
    justify-content: flex-end;

    .message-content {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 18px 18px 4px 18px;
    }
  }

  &.assistant {
    justify-content: flex-start;

    .message-content {
      background: white;
      color: #333;
      border-radius: 18px 18px 18px 4px;
      border: 1px solid #e0e0e0;
    }
  }
}

.message-content {
  max-width: 80%;
  padding: 10px 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-text {
  line-height: 1.4;
  word-wrap: break-word;
  
  // Markdown 样式
  :deep(.inline-code) {
    background: rgba(255, 255, 255, 0.2);
    padding: 2px 4px;
    border-radius: 3px;
    font-family: 'Courier New', monospace;
    font-size: 0.85em;
  }
  
  :deep(pre.hljs) {
    background: rgba(0, 0, 0, 0.1);
    padding: 8px;
    border-radius: 4px;
    overflow-x: auto;
    margin: 6px 0;
    font-size: 0.85em;
    
    code {
      background: none;
      padding: 0;
      font-family: 'Courier New', monospace;
    }
  }
  
  :deep(blockquote) {
    border-left: 3px solid rgba(255, 255, 255, 0.3);
    margin: 6px 0;
    padding: 6px 10px;
    background: rgba(255, 255, 255, 0.1);
    font-style: italic;
  }
  
  :deep(.markdown-table) {
    width: 100%;
    border-collapse: collapse;
    margin: 6px 0;
    font-size: 0.85em;
    
    th, td {
      border: 1px solid rgba(255, 255, 255, 0.2);
      padding: 4px 8px;
      text-align: left;
    }
    
    th {
      background: rgba(255, 255, 255, 0.1);
      font-weight: 600;
    }
  }
  
  :deep(ul, ol) {
    margin: 6px 0;
    padding-left: 16px;
    
    li {
      margin: 2px 0;
    }
  }
  
  :deep(h1, h2, h3, h4, h5, h6) {
    margin: 10px 0 6px 0;
    font-weight: 600;
    line-height: 1.2;
  }
  
  :deep(h1) { font-size: 1.2em; }
  :deep(h2) { font-size: 1.1em; }
  :deep(h3) { font-size: 1.05em; }
  
  :deep(p) {
    margin: 6px 0;
    line-height: 1.5;
  }
  
  :deep(a) {
    color: #87ceeb;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
  
  :deep(strong) {
    font-weight: 600;
  }
  
  :deep(em) {
    font-style: italic;
  }
  
  :deep(hr) {
    border: none;
    border-top: 1px solid rgba(255, 255, 255, 0.2);
    margin: 10px 0;
  }
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
  margin-top: 5px;
  text-align: right;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;

  span {
    width: 6px;
    height: 6px;
    background: #999;
    border-radius: 50%;
    animation: typing 1.4s infinite ease-in-out;

    &:nth-child(1) {
      animation-delay: -0.32s;
    }
    &:nth-child(2) {
      animation-delay: -0.16s;
    }
  }
}

@keyframes typing {
  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.input-area {
  padding: 15px;
  background: white;
  border-top: 1px solid #e0e0e0;
  cursor: default; // 输入区域不显示拖拽光标

  :deep(.el-input-group__append) {
    .el-button {
      border-radius: 0 4px 4px 0;
    }
  }
}
</style>